package com.example.pack;

import com.example.pack.util.ProjectDataUtil;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;

import java.io.File;
import java.io.IOException;

public class SaveController {
    @FXML
    private TextField projectName;

    @FXML
    private TextField svnPath;

    @FXML
    private TextField projectPath;

    @FXML
    private TextField classPath;

    @FXML
    private Label prompt;

    /**
     * 保存项目配置信息到JSON文件中
     * @param event
     */
    @FXML
    protected void doSave(ActionEvent event) {
        if (check()) {
            ProjectDataUtil.add(new WebProject(projectName.getText(),svnPath.getText(), projectPath.getText(), classPath.getText()));
            saveSuccess();
        }
    }

    /**
     * 校验数据正确性
     * @return false 项目信息有误 true 通过校验
     */
    public boolean check() {
        if (projectName.getText().isEmpty()) {
            prompt.setText("项目名称不能为空！");
            return false;
        }
        if (svnPath.getText().isEmpty()) {
            prompt.setText("项目SVN地址不能为空！");
            return false;
        }
        if(!executeCommandsToCheckSvnPath()){
            return false;
        }
        if (projectPath.getText().isEmpty()) {
            prompt.setText("项目本地路径不能为空！");
            return false;
        }
        if (!new File(projectPath.getText()).exists()) {
            prompt.setText("本地项目路径不存在！");
            return false;
        }
        if (classPath.getText().isEmpty()) {
            prompt.setText("classpath相对路径不能为空！");
            return false;
        }
        return true;
    }

    /**
     * 执行命令，校验svn地址是否能正常访问
     * @return true svn地址正确 false svn地址无法正常访问
     */
    public boolean executeCommandsToCheckSvnPath() {
        try {
            String command = "svn info " + svnPath.getText();
            Process process = Runtime.getRuntime().exec(command);
            process.getInputStream();
            int code = process.waitFor();
            if(code == 0){
                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        prompt.setText("项目SVN地址无法正常访问！");
        return false;
    }

    /**
     * 保存成功 清除已输入的数据
     */
    public void saveSuccess(){
        prompt.setText("保存成功");
        projectName.setText("");
        svnPath.setText("");
        projectPath.setText("");
    }
}
